<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class DingTalkSetting extends BaseModel
{
    use HasFactory;
    protected $table = 'dingtalk_setting';
    protected $guarded = [];
    public function _creating(&$model)
    {
        $model['creator_id'] = user()->id;
    }
    public function token()
    {
        return $this->hasMany(DingtalkToken::class, 'setting_id');
    }
    //获取token  cache
    public function get($accesstoken)
    {
        $data = $this->token->where(['accesstoken' => $accesstoken])->first();
        return $data && !$data->isOverTime() ? json_decode($data->value, true) : false;
    }
    //设置token cache
    public function set($accesstoken, $value, $time)
    {
        $token_data = [
            'accesstoken' => $accesstoken,
            'value' => json_encode($value),
            'time' => $time,
            'setting_id' => $this->id,
        ];

        return DingtalkToken::updateOrCreate(['accesstoken' => $accesstoken], $token_data);
    }
    //保存debug 日志
    public function debug($key, $data)
    {
        DingTalkLog::create(['key' => $key, 'data' => json_encode($data), 'creator_id' => $this->creator_id]);
    }
}
